import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import * as api from "@/http/api"
import Request from '@/http/jyRequest.js'
import Cache from '@/common/Cache.js'


const store = new Vuex.Store({
	state: {
		openId: '',
		unionId: '',
		token: '',
		communityList: '',//用户可选社区列表
		currentcommunityCode: '',//用户当前所在社区id
		currentcommunityName: '',//用户当前所在社区id
		failedMessage: '',//认证失败原因
		platformType: '',//平台类型 0: 微信,1: 平台,2: 浙里办
		platformToken: '',
		platformTicket: '',
		userInfo: '',//微信用户信息
		authStatus: '',//认证状态
		mobile: '',//用户手机号
		isRedirectUrl: false,
		scene: ''
	},
	mutations: {
		setOpenId(state, payload){
			state.openId = payload
		},
		setUnionId(state, payload){
			state.unionId = payload
		},
		setToken(state, payload){
			state.token = payload
		},
		setCommunityList(state, payload){
			state.communityList = payload
		},
		setCurrentCommunityCode(state, payload){
			state.currentcommunityCode = payload
		},
		setCurrentcommunityName(state, payload){
			state.currentcommunityName = payload
		},
		setFailedMessage(state, payload){
			state.failedMessage = payload
		},
		setPlatformType(state, payload){
			state.platformType = payload
		},
		setPlatformToken(state, payload){
			state.platformToken = payload
		},
		setPlatformTicket(state, payload){
			state.platformTicket = payload
		},
		setUserInfo(state, payload){
			state.userInfo = payload
		},
		setAuthStatus(state,payload){
			state.authStatus = payload
		},
		setUserMobile(state,payload){
			state.mobile = payload
		},
		setIsRedirectUrl(state,payload){
			state.isRedirectUrl = payload
		},
		setScene(state,payload){
			state.scene = payload
		}
	},
	actions: {
		// 获取openId
		async getUserOpenId({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.unionId) {
					resolve(state.unionId)
				} else {
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success: (res) => {
							console.log(res);
							let data = {
								code: res.code,
							};
							Request.fetch({
								url: api.userMsg,
								data: data,
							}).then(res => {
								console.log(12,res.openId)
								// commit('setOpenId', 'oA61j5awwIiuZ15Ydzerjhs-MVFQ' ||res.openId);
								commit('setOpenId', res.openId);
								commit('setUnionId', res.unionId);
								commit('setUserInfo',{
									avatarUrl: res.avatarUrl,
									city: res.city,
									country: res.country,
									language: res.language,
									gender: res.gender,// 性别 0：未知、1：男、2：女
									nickName: res.nickName,
									province: res.province,
								})
								resolve()
							})
						},
						fail: (err) => {
							reject(err)
						}
					})
					// #endif
				}
			})
		},
		// 各平台鉴权
		async platformAuth({
			commit,
			state
		},isWechat = true) {
			return await new Promise((resolve, reject) => {
				let data = {
					client_id: '3df99e5bf8',
					client_secret: '104e458c343fae65e38139',
					scopes: 'all',
				}
				switch(state.platformType){
					case 1:
						// 平台鉴权
						data = {
							...data,
							grant_type: 'platform_token',
							token: state.platformToken
						}
					break;
					case 2:
						// 浙里办鉴权
						data = {
							 ...data,
							grant_type: 'platform_token',
							ticket: state.platformTicket
						}
					break;
					default:
					// 'oA61j5awwIiuZ15Ydzerjhs-MVFQ'
						data = {
							...data,
							grant_type: 'wechat',
							open_id: state.openId
						}
					break;
				}
				Request.fetch({
					url: api.platformAuth,
					data: data,
				}).then(res => {
					const { access_token = '' } = res;
					if(access_token){
						commit('setToken',access_token)
						Cache.set('_token',access_token)
					}else{ //用户不存在跳转注册页
						uni.reLaunch({
							url: '/pages/login/index/index'
						})
					}
					resolve()
				})
			})
		},
		// 获取用户状态
		async getUserStatus({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				Request.fetch({
					url: api.userStatus,
					method: 'GET'
				}).then(res => {
					const { communityList = [],currentCommunityCode = '',failedMessage = '',status = '',mobile} = res
					let communityName = ''
					communityList.some(item => {
						if(item.code === currentCommunityCode)
							communityName = item.name
					})
					commit('setCommunityList', communityList)
					commit('setCurrentCommunityCode', currentCommunityCode)
					commit('setFailedMessage', failedMessage)
					commit('setAuthStatus',status)
					commit('setCurrentcommunityName',communityName)
					commit('setUserMobile',mobile)
					console.log('isRedirectUrl',state.isRedirectUrl)
					if(state.isRedirectUrl){
						resolve()
						return
					} 
					// 如果是登录页调用直接返回
					if(!Cache.get('isLogin')){
						// 判断状态
						switch(status){
							case 'AUTHENTICATING':
							// 认证中 ->审核中页面
								uni.reLaunch({
									url: '/pages/community/approving/approving'
								})
							break; 
							case 'AUTHENTICATION_FAILED':
							// 认证失败 ->社区认证
								uni.navigateTo({
									url: `/pages/community/index/index?isFailed=true`
								})
							break;
							default:
								uni.reLaunch({
									url: '/pages/tabBar/index/indexNew'
								})
							break;
						}
					}
					resolve()
				})
			})
		},
	}
})
export default store
